﻿using Common.Db.SysDb;
using Common.Tool;
using Common.Tool.FileTools;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Db
{
    public static class SysDbHelper
    {
        public static List<string> loginUsers = new List<string>();
        /// <summary>
        /// 数据库
        /// </summary>
        /// <summary>
        /// 权限数据库
        /// </summary>
        public static SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = $"Data Source={Environment.CurrentDirectory}\\db\\Sys.db",
            DbType = DbType.Sqlite,
            IsAutoCloseConnection = true
        }, db =>
        {
            db.Aop.OnError = ex =>
            {
                //LogHelper.Error("Sysdb Error", ex);
            };
            //不存在创建数据库，存在不会创建
            db.DbMaintenance.CreateDatabase();
            //创建表根据实体类
            db.CodeFirst.InitTables(typeof(User), typeof(Role), typeof(Config), typeof(Alarm));
        });
        /// <summary>
        /// 初始化权限数据库
        /// </summary>
        public static void IniSysDb()
        {

            //初始化数据
            if (!db.Queryable<User>().Any())
            {
                var dt = db.GetDate();
                var users = new List<User>()
                {
                    new User ()
                    {
                        Id=1,
                        LoginName="Admin",
                        Fingerprint=string.Empty,
                        Face=string.Empty,
                        Password="8ik,9ol.",
                        Group="A",
                        RoleIds =new List<int>{ 1},
                        IsAdmin=true,
                        Time=dt,
                    },
                    new User ()
                    {
                        Id=2,
                        LoginName="Operator",
                        Fingerprint=string.Empty,
                        Face=string.Empty,
                        Password="1",
                        Group="A",
                        RoleIds =new List<int>{ 2},
                        IsAdmin=false,
                        Time=dt,
                    },
                };
                var roles = new List<Role>()
                {
                    new Role ()
                    {
                        Id=1,
                        Name="Admin",
                        IsAdmin=true,
                        Time=dt,
                    },
                    new Role ()
                    {
                        Id=2,
                        Name="Operator",
                        Auths=new List<int>{ 1,2},
                        IsAdmin=false,
                        Time=dt,
                    },
                };
                var config = new List<Config>()
                {
                    new Config ()
                    {
                        Id=1,
                        Key="LoginUser",
                        Value="Admin"
                    },
                };
                db.Insertable(config).ExecuteCommand();
                db.Insertable(users).ExecuteCommand();
                db.Insertable(roles).ExecuteCommand();
            }

        }
        /// <summary>
        /// 账号登录
        /// </summary>
        /// <param name="name">账号</param>
        /// <param name="pass">密码</param>
        /// <param name="msg">返回消息</param>
        /// <returns></returns>
        public static SysDb.User login(string name, string pass, ref string msg)
        {
            //查询账号
            var user = db.Queryable<User>().First(o => o.LoginName == name);
            if (user == null)
            {
                msg = Properties.Lang.账号不存在;
                return null;
            }
            //比对密码
            if (!string.IsNullOrEmpty(user.Password) && user.Password != pass)
            {
                msg = Properties.Lang.密码错误;
                return null;
            }
            UploadLoginUsers(name);
            return user;
        }
        /// <summary>
        /// 获取历史登录账号
        /// </summary>
        /// <returns></returns>
        public static List<string> GetLoginUsers()
        {
            //历史账号转List
            loginUsers = db.Queryable<Config>().Where(o => o.Key == "LoginUser").Select(o => o.Value).First()?.Split(';').ToList() ?? new List<string>();
            return loginUsers;
        }
        /// <summary>
        /// 新增登录记录
        /// </summary>
        /// <returns></returns>
        public static bool UploadLoginUsers(string name)
        {
            //空账号或已有记录
            if (string.IsNullOrEmpty(name) || loginUsers.Contains(name))
                return true;
            return db.Updateable<Config>().SetColumns(o => o.Value == (o.Value + ";" + name)).Where(o => o.Key == "LoginUser").ExecuteCommand() > 0;
        }

        public static List<Role> GetAllRole()
        {
            return db.Queryable<Role>().Where(o => !o.IsAdmin).ToList();
        }
        public static bool CheckUserName(int id, string name)
        {
            return db.Queryable<User>().Where(o => o.Id != id && o.LoginName == name).Any();
        }
        public static bool UpdpateUser(User user)
        {
            return db.Updateable(user).ExecuteCommand() == 1;
        }
        public static bool InsertUser(User user)
        {
            return db.Insertable(user).ExecuteCommand() == 1;
        }
        public static List<User> GetAllUser()
        {
            return db.Queryable<User>().ToList();
        }
    }
}
